﻿//ConsoleLogListener.cs
//Copyright (c) 2013 StockSharp LLC, all rights reserved.
//This code module is part of StockSharp library.
//This code is licensed under the GNU GENERAL PUBLIC LICENSE Version 3.
//See the file License.txt for the license details.
//More info on: http://stocksharp.com

namespace StockSharp.Logging
{
	using System;

	using Ecng.Common;
	using Ecng.Interop;

	/// <summary>
	/// Логгер, записывающий данные в консольное окно.
	/// </summary>
	public class ConsoleLogListener : LogListener
	{
		private readonly object _lock = new object();

		/// <summary>
		/// Создать <see cref="ConsoleLogListener"/>.
		/// </summary>
		public ConsoleLogListener()
		{
			if (!WinApi.AllocateConsole())
				throw new InvalidOperationException("Невозможно создать консольное окно.");
		}

		/// <summary>
		/// Записать сообщение.
		/// </summary>
		/// <param name="message">Отладочное сообщение.</param>
		protected override void OnWriteMessage(LogMessage message)
		{
			ConsoleColor color;

			switch (message.Level)
			{
				case LogLevels.Debug:
				case LogLevels.Info:
					color = ConsoleHelper.Info;
					break;
				case LogLevels.Warning:
					color = ConsoleHelper.Warning;
					break;
				case LogLevels.Error:
					color = ConsoleHelper.Error;
					break;
				default:
					throw new ArgumentOutOfRangeException("message");
			}

			var newLine = "{0} | {1, -15} | {2}".Put(message.Time.ToString(TimeFormat), message.Source.Name, message.Message);

			lock (_lock)
				newLine.ConsoleWithColor(color);
		}
	}
}